package customer

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"server/global"
	"server/model/common/response"
	customerReq "server/model/customer/request"
	"server/utils"
)

// AddOrUpdateFile 添加/更新客户文件
func (ca *CustomerApi) AddOrUpdateFile(c *gin.Context) {
	var file customerReq.CustomerFile
	_ = c.ShouldBindJSON(&file)

	// 参数校验
	validate := validator.New()
	if err := validate.Struct(&file); err != nil {
		msg := fmt.Sprintf("请求参数错误,error: %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("请求参数错误", zap.Error(err))
		return
	}

	// 必须校验每一个fileinfo的切片中必须有Key(暂时不需要了，改成分片上传文件了)
	//if err := file.Validate(); err != nil {
	//	msg := fmt.Sprintf("请求参数错误,error: %s", err)
	//	response.FailWithMessage(msg, c)
	//	global.TD27_LOG.Error("请求参数错误", zap.Error(err))
	//	return
	//}

	if res, action, err := customerService.AddOrUpdateFile(file); err != nil {
		msg := fmt.Sprintf("%s失败, %s", action, err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("添加失败", zap.Error(err))
	} else {
		msg := fmt.Sprintf("%s成功", action)
		response.OkWithDetailed(res, msg, c)
	}
}

// GetCustomerFile    获取客户文件
func (ca *CustomerApi) GetCustomerFile(c *gin.Context) {
	var FileSp customerReq.FileSearchParams
	FileSp.Page, _ = utils.StringToInt(c.Query("currentPage"))
	FileSp.PageSize, _ = utils.StringToInt(c.Query("size"))
	FileSp.CustomerName = c.Query("name")
	FileSp.FileKeyword = c.Query("fileName")
	FileSp.CustomerID, _ = utils.StringToUint(c.Query("customerId"))

	if list, total, err := customerService.GetCustomerFile(FileSp); err != nil {
		response.FailWithMessage("获取失败", c)
		global.TD27_LOG.Error("获取客户列表失败", zap.Error(err))
	} else {
		response.OkWithDetailed(response.PageResult{
			Page:     FileSp.Page,
			PageSize: FileSp.PageSize,
			Total:    total,
			List:     list,
		}, "获取成功", c)
	}
}

// DeleteCustomerFile 删除客户文件
func (ca *CustomerApi) DeleteCustomerFile(c *gin.Context) {
	id, _ := utils.StringToInt(c.Param("fileId"))
	key := c.Query("key")

	if msg, err := customerService.DeleteCustomerFile(id, key); err != nil {
		m := fmt.Sprintf("删除失败，Detail: %v,error: %s", msg, err)
		response.FailWithMessage(m, c)
		global.TD27_LOG.Error(m)
	} else {
		response.OkWithDetailed(msg, "删除成功", c)
	}
}
